package com.zmn.oms.services.config;

import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ES集群配置
 */
@Setter
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {

    public static final String ES_CLIENT_M1 = "es_client_m1";

    public static final String ES_CLIENT_M2 = "es_client_m2";

    private Connect m1;

    private Connect m2;

    /**
     * 客户端1
     */
    @Bean(name = ES_CLIENT_M1, destroyMethod = "close")
    public RestHighLevelClient masterRestHighLevelClient() {
        return getRestHighLevelClient(m1);
    }

    /**
     * 客户端2
     */
    @Bean(name = ES_CLIENT_M2, destroyMethod = "close")
    public RestHighLevelClient secondRestHighLevelClient() {
        return getRestHighLevelClient(m2);
    }

    private RestHighLevelClient getRestHighLevelClient(Connect connect) {
        String[] hosts = connect.getHosts().split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length];
        for (int i = 0; i < hosts.length; i++) {
            httpHosts[i] = HttpHost.create(hosts[i]);
        }
        RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
        //配置身份验证
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(connect.getUsername(), connect.getPassword()));
        restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(restClientBuilder);
    }


    @Setter
    @Getter
    public static class Connect {
        private String hosts;
        private String username;
        private String password;
    }
}
